<script setup lang="ts">
// import type { FormRules } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'
import { ref } from 'vue'

/**
 * @description 定义一个登录的数据类型
 */
interface FormData {
  username: string
  password: string
}
const formData = ref<FormData>({
  username: '',
  password: ' ',
})
/**
 * 定义校验规则
 */
const formRules = ref<FormRules<FormData>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 15, message: '用户名长度为5-15', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-0]{8}$/, message: '请输入8位密码', trigger: 'blur' },
  ],
})

const loginFormRef = ref<FormInstance>()
/**
 * 重置账号和密码
 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

/**登录 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('校验通过')
    } else {
      console.log('校验未通过!', fields)
    }
  })
}
</script>

<template>
  <div class="container">
    <div class="login-form">
      <h3 class="login-title">智慧园区-登录</h3>
      <el-form
        label-width="auto"
        style="max-width: 600px"
        ref="loginFormRef"
        :model="formData"
        :rules="formRules"
      >
        <el-form-item label="账号" prop="username">
          <el-input placeholder="请输入账号" v-model="formData.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            show-password
            placeholder="请输入密码"
            v-model="formData.password"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox> 记住我 </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(loginFormRef)"> 登录 </el-button>
          <el-button @click="resetForm(loginFormRef)"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login-form {
  width: 500px;
  max-height: 400px;
  box-shadow: 0 0 10px gray;
  margin: 100px auto;
  padding: 50px;
}

.login-title {
  text-align: center;
  padding: 20px 0;
}
</style>
